//
//  ActionSheetView.swift
//  CWActionSheet
//
//  Created by chenwei on 2017/8/31.
//  Copyright © 2017年 cwwise. All rights reserved.
//


import UIKit

public enum VHLActionSheetButtonType: Equatable {
    case cancel
    case ok
    case dismiss
    case other(Int)
    
    public static func ==(lhs: VHLActionSheetButtonType, rhs: VHLActionSheetButtonType) -> Bool {
        switch (lhs, rhs) {
        case (.cancel, .cancel), (.ok, .ok) ,(.dismiss, .dismiss):
            return true
        case (let .other(lhsIndex), let .other(rhsIndex)):
            return lhsIndex == rhsIndex
        default:
            return false
        }
    }
}

/// 点击回调
public typealias VHLActionSheetClickedHandler = ((VHLActionSheetView, VHLActionSheetButtonType) -> Void)

private class VHLActionSheetContainerView: UIView {
    override func layoutSubviews() {
        super.layoutSubviews()
//        if let sView = self.superview {
//            sView.setNeedsLayout()
//        }
    }
}
private class VHLActionSheetTableView: UITableView {
    override func layoutSubviews() {
        super.layoutSubviews()
        if let sView = self.superview {
            sView.layoutIfNeeded()
        }
    }
}
public class VHLActionSheetCell: UITableViewCell {
    
    public var titleLabel: UILabel = {
        let titleLabel = UILabel()
        titleLabel.backgroundColor = UIColor.clear
        titleLabel.textAlignment = .center
        titleLabel.numberOfLines = 1
        return titleLabel
    }()
    
    var lineLayer: CALayer = {
        let lineLayer = CALayer()
        return lineLayer
    }()
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        self.contentView.layer.addSublayer(lineLayer)
        self.contentView.addSubview(titleLabel)
        self.selectedBackgroundView = UIView()
    }
    
    override public func layoutSubviews() {
        super.layoutSubviews()
        lineLayer.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: 1/UIScreen.main.scale)
        titleLabel.frame = CGRect(x: 0, y: 10, width: self.bounds.width, height: self.bounds.height-2*10)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override public func awakeFromNib() {
        super.awakeFromNib()
    }
    
    override public func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)
        
        // Configure the view for the selected state
    }
}

public class VHLActionSheetView: UIView {

    // MARK: 属性
    /// 阴影背景视图
    private var backgroundEffectView: UIView = UIView()
    
    /// topView 标题顶部的 view
    public var topView: UIView?
    /// 标题
    public var title: String?
    /// 副标题
    public var subTitle: String?
    /// 自定义视图，会添加到标题下面，按钮上面
    public var headerView: UIView?
    /// ok按钮title
    public var okButtonTitle: String?
    /// 取消按钮title
    public var cancelButtonTitle: String?
    /// 显示按钮数量 （不能为负数）
    public var visibleButtonCount: NSInteger = 0
    /// 默认选中的按钮下标数组
    public var selectedButtonIndexs: [Int] = []
    /// destructive按钮位置。从 otherButtonTitles 中从 0 开始
    public var destructiveButtonIndexs: [Int] = []
    /// cell make 的handler 默认的不支持的话可以自己定义
    public var makeCellHander: ((VHLActionSheetCell, IndexPath) -> Void)?
    /// 默认配置
    public var config: VHLActionSheetConfig = VHLActionSheetConfig() {
        didSet {
            config.actionSheetView = self
        }
    }
    /// 背景是否可点击
    public var backgroundTapEnable: Bool = true
    /// 点击事件回调
    public var clickedHandler: VHLActionSheetClickedHandler?
    
    /// 其他按钮标题
    private var otherButtonTitles: [String] = []
    /// 内容View
    private var containerView: VHLActionSheetContainerView!
    /// 标题
    private var titleLabel: UILabel!
    /// 副标题
    private var subTitleLabel: UILabel!
    /// 其他按钮tableView
    private var tableView: VHLActionSheetTableView!
    /// 分割线
    private var cancelButtonTopView: UIView!
    /// 确定按钮
    private var okButton: UIButton!
    /// 取消按钮
    private var cancelButton: UIButton!
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    private convenience init() {
        var frame = UIScreen.main.bounds
        if let windowFrame = UIApplication.shared.windows.filter({ $0.isKeyWindow }).first?.bounds {
            frame = windowFrame
        }
        self.init(frame: frame)
    }
    
    private override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        self.config.actionSheetView = self
    }
    
    /// 初始化方法
    ///
    /// - Parameters:
    ///   - title: 标题
    ///   - cancelButtonTitle: 取消按钮标题
    ///   - otherButtonTitles: 其他按钮数组
    ///   - clickedHandler: 点击事件回调
    public convenience init(title: String? = nil,
                            okButtonTitle: String? = nil,
                            cancelButtonTitle: String? = nil,
                            otherButtonTitles: [String] = [],
                            config: VHLActionSheetConfig = VHLActionSheetConfig(),
                            clickedHandler: VHLActionSheetClickedHandler? = nil) {
        self.init()
        self.title = title
        self.okButtonTitle = okButtonTitle
        self.cancelButtonTitle = cancelButtonTitle
        self.otherButtonTitles = otherButtonTitles
        
        self.config = config
        self.config.actionSheetView = self
        self.clickedHandler = clickedHandler
    }

    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    // MARK: 初始化
    func setupUI() {
        backgroundEffectView.frame = self.bounds
        backgroundEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        addSubview(backgroundEffectView)
        
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(backgroundViewClicked))
        backgroundEffectView.addGestureRecognizer(tapGesture)
        
        // -----------------------------------------------------------------------
        containerView = VHLActionSheetContainerView()
        addSubview(containerView)
        
        titleLabel = UILabel()
        titleLabel.backgroundColor = UIColor.clear
        titleLabel.textAlignment = .center
        containerView.addSubview(titleLabel)
        
        subTitleLabel = UILabel()
        subTitleLabel.backgroundColor = UIColor.clear
        subTitleLabel.textAlignment = .center
        containerView.addSubview(subTitleLabel)

        //
        tableView = VHLActionSheetTableView(frame: CGRect.zero, style: .plain)
        tableView.backgroundColor = UIColor.clear
        tableView.estimatedRowHeight = 0
        tableView.estimatedSectionHeaderHeight = 0
        tableView.estimatedSectionFooterHeight = 0
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        containerView.addSubview(tableView)
        
        if #available(iOS 13.0, *) {
            if config.cellStyle != .system {
                if config.cellStyle == .dark {
                    tableView.overrideUserInterfaceStyle = .dark
                } else {
                    tableView.overrideUserInterfaceStyle = .light
                }
            }
        }
        
        // 取消按钮顶部分割线
        cancelButtonTopView = UIView()
        containerView.addSubview(cancelButtonTopView)
        
        // ok button
        okButton = UIButton(type: .custom)
        okButton.addTarget(self, action: #selector(fixationButtonClicked(sender:)), for: .touchUpInside)
        okButton.tag = 0
        containerView.addSubview(okButton)
        
        // 取消按钮
        cancelButton = UIButton(type: .custom)
        cancelButton.addTarget(self, action: #selector(fixationButtonClicked(sender:)), for: .touchUpInside)
        cancelButton.tag = 1
        containerView.addSubview(cancelButton)
    }
    // MARK: 计算布局
    public override func layoutSubviews() {
        super.layoutSubviews()
        setupSubViews()
    }
    public override func layoutIfNeeded() {
        super.layoutIfNeeded()
        setupSubViews()
    }
    
    func setupSubViews() {
        backgroundEffectView.frame = self.bounds
        
        containerView.layer.cornerRadius = config.actionSheetCornerRadius
        containerView.backgroundColor = config.actionSheetBackgroundColor
        
        titleLabel.font = config.titleFont
        titleLabel.textColor = config.titleColor
        titleLabel.numberOfLines = config.titleLinesNumber
        titleLabel.text = title
        
        subTitleLabel.font = config.subTitleFont
        subTitleLabel.textColor = config.subTitleColor
        subTitleLabel.numberOfLines = config.subTitleLinesNumber
        subTitleLabel.text = subTitle
    
        /// 计算布局
        let containerX = config.outerEdgeInsets.left
        let containerWidth = self.frame.width - containerX - config.outerEdgeInsets.right
        var containerMaxHeight = self.frame.height - config.outerEdgeInsets.top - config.outerEdgeInsets.bottom
        if #available(iOS 11.0, *) {
            containerMaxHeight -= safeAreaInsets.top
        }
        let contentWidth = containerWidth - config.innerEdgeInsets.left - config.innerEdgeInsets.right
        
        // 标题之上的视图
        var topStart: CGFloat = config.innerEdgeInsets.top
        if topView != nil && (topView?.frame.size.height)! > 0.0 {
            topView?.removeFromSuperview()
            containerView.addSubview(topView!)
            topView?.frame = CGRect(x: config.innerEdgeInsets.left, y: config.innerEdgeInsets.top, width: contentWidth, height: topView!.frame.size.height)
            topStart = topView!.frame.maxY
        }
        
        // 标题 frame
        let titleX = config.innerEdgeInsets.left + config.titleEdgeInsets.left
        let titleWidth = contentWidth - config.titleEdgeInsets.left - config.titleEdgeInsets.right
        
        if title != nil && title != "" {
            let size = CGSize(width: titleWidth,
                              height: CGFloat.greatestFiniteMagnitude)
            var titleSize = titleLabel.sizeThatFits(size)
            titleSize = CGSize(width: titleWidth, height: ceil(titleSize.height)+1)
            
            titleLabel.frame = CGRect(x: titleX,
                                      y: topStart + config.titleEdgeInsets.top,
                                      width: titleWidth,
                                      height: max(24, titleSize.height))
        } else {
            titleLabel.frame = CGRect(x: config.innerEdgeInsets.left + config.titleEdgeInsets.left, y: topStart, width: contentWidth, height: 0)
        }
        // 副标题 frame
        if subTitle != nil && subTitle != "" {
            let size = CGSize(width: titleWidth,
                              height: CGFloat.greatestFiniteMagnitude)
            var subTitleSize = subTitleLabel.sizeThatFits(size)
            subTitleSize = CGSize(width: titleWidth, height: ceil(subTitleSize.height)+1)
            
            var sTitleY = titleLabel.frame.maxY + config.titleEdgeInsets.bottom + config.subtitleEdgeInsets.top
            if titleLabel.frame.height == 0 {
                sTitleY = titleLabel.frame.maxY + config.titleEdgeInsets.top
            }
            subTitleLabel.frame = CGRect(x: titleX,
                                         y: sTitleY,
                                      width: titleWidth,
                                      height: max(24, subTitleSize.height))
        } else {
            var subTitleY = titleLabel.frame.maxY + config.titleEdgeInsets.bottom
            if titleLabel.frame.size.height == 0 {
                subTitleY = titleLabel.frame.maxY
            }
            subTitleLabel.frame = CGRect(x: config.innerEdgeInsets.left + config.titleEdgeInsets.left,
                                         y: subTitleY,
                                         width: contentWidth,
                                         height: 0)
        }
        // tableView
        let cancelButtonTopLineHeight: CGFloat = (cancelButtonTitle != nil || okButtonTitle != nil) ? config.cancelButtonTopLineHeight : 0.0
        let okButtonHeight = okButtonTitle != nil ? config.fixedButtonHeight : 0
        let cancelButtonHeight = cancelButtonTitle != nil ? config.fixedButtonHeight : 0
        
        var tableViewY = subTitleLabel.frame.maxY + config.subtitleEdgeInsets.bottom
            + config.cancelButtonTopLineHeight
        // 计算 tableView 的最大高度，不超过屏幕高度
        let tableViewMaxHeight = containerMaxHeight - tableViewY - cancelButtonTopLineHeight - cancelButtonHeight - config.innerEdgeInsets.bottom
        
        var tableViewHeight: CGFloat
        if visibleButtonCount > 0 && Int(visibleButtonCount) < otherButtonTitles.count {
            tableViewHeight = ceil(CGFloat(visibleButtonCount) * config.buttonHeight)
        } else {
            tableViewHeight = CGFloat(otherButtonTitles.count) * config.buttonHeight
        }
        // 添加自定义顶部视图 headerView
        if headerView != nil && (headerView?.frame.size.height)! > 0.0 {
            headerView?.frame.size.width = containerWidth
            tableViewHeight += (headerView?.frame.size.height)!
            tableView.tableHeaderView = headerView
        } else {
            tableView.tableHeaderView = nil
        }
        
        if tableViewHeight > tableViewMaxHeight {
            tableView.isScrollEnabled = true
        }
        tableViewHeight = min(tableViewHeight, tableViewMaxHeight)
        
        // tableview y
        if (titleLabel.frame.size.height == 0 && subTitleLabel.frame.size.height == 0) {
            tableViewY = subTitleLabel.frame.maxY
        }
        
        tableView.rowHeight = config.buttonHeight
        tableView.frame = CGRect(x: 0,
                                 y: tableViewY,
                                 width: containerWidth,
                                 height: tableViewHeight)
        
        // 取消按钮顶部分隔视图
        cancelButtonTopView.frame = CGRect(x: config.innerEdgeInsets.left, y: tableView.frame.maxY,
                                     width: contentWidth, height: cancelButtonTopLineHeight)
        cancelButtonTopView.backgroundColor = config.cancelButtonTopLineColor
        
        /// 底部固定按钮。新增底部按钮排列，横排和竖排
        var bottomButtonWidth = contentWidth
        if okButtonHeight > 0 && cancelButtonHeight > 0 && config.bottomButtonArrangement == .horizontal {
            bottomButtonWidth = (contentWidth - config.innerEdgeInsets.left) / 2
        }
        // ok按钮
        okButton.titleLabel?.font = config.buttonFont
        okButton.setTitleColor(config.okButtonTitleColor, for: .normal)
        okButton.setBackgroundImage(UIImage(vhl_color: config.okButtonBGColor), for: .normal)
        okButton.setBackgroundImage(UIImage(vhl_color: config.okButtonHighlightdBGColor), for: .highlighted)
        okButton.layer.cornerRadius = config.fixedButtonCornerRadius  // buttonCornerRadius
        okButton.layer.masksToBounds = true
        okButton.setTitle(okButtonTitle, for: .normal)
        
        if bottomButtonWidth < contentWidth {       // 横着并排底部固定按钮
            okButton.frame = CGRect(x: config.innerEdgeInsets.left * 2 + bottomButtonWidth, y: cancelButtonTopView.frame.maxY,
                                    width: bottomButtonWidth, height: okButtonHeight)
        } else {
            okButton.frame = CGRect(x: config.innerEdgeInsets.left, y: cancelButtonTopView.frame.maxY,
                                    width: contentWidth, height: okButtonHeight)
        }
        
        // 取消按钮
        cancelButton.titleLabel?.font = config.buttonFont
        cancelButton.setTitleColor(config.cancelButtonTitleColor, for: .normal)
        cancelButton.setBackgroundImage(UIImage(vhl_color: config.cancelButtonBGColor), for: .normal)
        cancelButton.setBackgroundImage(UIImage(vhl_color: config.cancelButtonHighlightdBGColor), for: .highlighted)
        cancelButton.layer.cornerRadius = config.fixedButtonCornerRadius
        cancelButton.layer.masksToBounds = true
        cancelButton.setTitle(cancelButtonTitle, for: .normal)
        
        if bottomButtonWidth < contentWidth {       // 横着并排底部固定按钮
            cancelButton.frame = CGRect(x: config.innerEdgeInsets.left, y: cancelButtonTopView.frame.maxY,
                                    width: bottomButtonWidth, height: cancelButtonHeight)
        } else {
            let cancelOffsetBottom = ((okButtonHeight > 0 && cancelButtonHeight > 0) ? config.innerEdgeInsets.bottom : 0) / 2
            cancelButton.frame = CGRect(x: config.innerEdgeInsets.left,
                                        y: okButton.frame.maxY + cancelOffsetBottom,
                                        width: contentWidth,
                                        height: cancelButtonHeight)
        }
        
        let containerHeight = cancelButton.frame.maxY + config.innerEdgeInsets.bottom
        let containerY = self.frame.height - cancelButton.frame.maxY - config.outerEdgeInsets.bottom - config.innerEdgeInsets.bottom
        
        containerView.frame = CGRect(x: containerX,
                                     y: containerY,
                                     width: containerWidth,
                                     height: containerHeight)
        tableView.reloadData()
    }
}
// MARK: - button action
extension VHLActionSheetView {
    @objc func backgroundViewClicked() {
        if !backgroundTapEnable { return }
        dismiss()
    }
    
    @objc func fixationButtonClicked(sender: UIButton) {
        if sender.tag == 0 {
            self.clickedHandler?(self, .ok)
        } else {
            self.clickedHandler?(self, .cancel)
        }
        hideWithButtonIndex(0)
    }
    
    func hideWithButtonIndex(_ index: Int) {
        UIView.animate(withDuration: config.animationDuration, delay: 0, options: .curveEaseOut, animations: {
            var frame = self.containerView.frame
            frame.origin.y = self.frame.size.height
            
            self.containerView.frame = frame
            
            //self.backgroundEffectView.colorTintAlpha = 0.0
            self.backgroundEffectView.alpha = 0.0
        }, completion: {(finished) in
            self.clickedHandler = nil
            self.makeCellHander = nil
            
            self.alpha = 0.0
            self.removeFromSuperview()
        })
    }
}
// MARK: - Delegate - UITableView
extension VHLActionSheetView: UITableViewDelegate, UITableViewDataSource {
    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return otherButtonTitles.count
    }
    
    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        var cell = tableView.dequeueReusableCell(withIdentifier: "cell") as? VHLActionSheetCell
        if cell == nil {
            cell = VHLActionSheetCell(style: .value1, reuseIdentifier: "cell")
        }
        // 圆角
        cell?.layer.cornerRadius = config.buttonCornerRadius
        cell?.layer.masksToBounds = true
        // 分割线
        cell?.lineLayer.backgroundColor = config.separatorColor.cgColor
        if indexPath.row == 0 && title == nil && subTitle == nil {
            cell?.lineLayer.backgroundColor = UIColor.clear.cgColor
        }
        // 标题
        cell?.textLabel?.font = config.buttonFont
        cell?.textLabel?.textColor = config.buttonTitleColor
        
        cell?.titleLabel.font = config.buttonFont
        cell?.titleLabel.textColor = config.buttonTitleColor
        cell?.tintColor = config.buttonTitleColor
        // 副标题
        cell?.detailTextLabel?.font = config.buttonFont
        cell?.detailTextLabel?.textColor = config.subTitleColor
        
        cell?.titleLabel.text = otherButtonTitles[indexPath.row]
        // 背景
        cell?.backgroundColor = config.buttonBGColor
        cell?.selectedBackgroundView?.backgroundColor = config.buttonHighlightdBGColor
        //
        cell?.accessoryType = .none
        // 选中样式
        if selectedButtonIndexs.contains(indexPath.row) {
            cell?.backgroundColor = config.buttonHighlightdBGColor
        }
        
        // 破坏性按钮样式
        if destructiveButtonIndexs.contains(indexPath.row) {
            cell?.titleLabel.textColor = config.destructiveButtonTitleColor
            cell?.backgroundColor = config.destructiveButtonColor
            cell?.selectedBackgroundView?.backgroundColor = config.destructiveButtonHighlightdColor
        }
        // 可自定义 cell 的样式
        if let makeCellH = self.makeCellHander {
            cell?.titleLabel.text = ""
            makeCellH(cell!, indexPath)
        }
        
        return cell!
    }
    
    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        self.clickedHandler?(self, .other(indexPath.row))
        hideWithButtonIndex(indexPath.row+1)
    }
}
// MARK: - public method
public extension VHLActionSheetView {
    /// 添加按钮
    ///
    /// - Parameters:
    ///   - buttonTitles: 标题数组
    public func append(buttonTitles: [String]) {
        otherButtonTitles.append(contentsOf: buttonTitles)
        setupSubViews()
    }
    
    /// 在指定位置插入按钮
    ///
    /// - Parameters:
    ///   - buttonTitles: 标题数组
    ///   - index: 位置
    public func insert(buttonTitles: [String], at index: Int) {
        var innerIndex = index
        if index < 0 { innerIndex = 0 }
        if index > otherButtonTitles.count { innerIndex = otherButtonTitles.count }
        
        otherButtonTitles.insert(contentsOf: buttonTitles, at: innerIndex)
        setupSubViews()
    }
    
    /// 显示 ActionSheetView, cancelIndex: 0; otherButtonIndex 从 1 开始; dismiss -1; okButtonIndex 999
    public func show(in view: UIView? = nil) {
        var parentView = view
        if parentView == nil {
            parentView = UIApplication.shared.windows.filter({ $0.isKeyWindow }).first
        }
        guard let keyWindow = parentView else { return }
        self.removeFromSuperview()
        keyWindow.addSubview(self)
        // 增加 edege 约束
        self.translatesAutoresizingMaskIntoConstraints = false
        self.topAnchor.constraint(equalTo: keyWindow.topAnchor).isActive = true
        self.bottomAnchor.constraint(equalTo: keyWindow.bottomAnchor).isActive = true
        self.leadingAnchor.constraint(equalTo: keyWindow.leadingAnchor).isActive = true
        self.trailingAnchor.constraint(equalTo: keyWindow.trailingAnchor).isActive = true
        
        setupSubViews()
        containerView.frame = containerView.frame.offsetBy(dx: 0, dy: containerView.frame.height)
        
        self.backgroundEffectView.backgroundColor = .clear
        self.backgroundEffectView.alpha = 0.0
        UIView.animate(withDuration: config.animationDuration, delay: 0, options: .curveEaseOut, animations: {
            
            let frame = self.containerView.frame
            self.containerView.frame = frame.offsetBy(dx: 0, dy: -frame.height)
            
            //self.backgroundEffectView.blurRadius = self.config.bgCoverRadius
            //self.backgroundEffectView.colorTint = self.config.bgCoverColor
            //self.backgroundEffectView.colorTintAlpha = self.config.bgCoverAlpha
            self.backgroundEffectView.backgroundColor = self.config.bgCoverColor
            self.backgroundEffectView.alpha = self.config.bgCoverAlpha
        }, completion: {(finished) in
            self.backgroundEffectView.isUserInteractionEnabled = self.config.canTouchToDismiss
            
            // 如果 otherButtons 可滚动，给个向上滚动的提示动画（已去掉动画）
            if (self.visibleButtonCount > 0 && Int(self.visibleButtonCount) < self.otherButtonTitles.count) ||
                (self.tableView.frame.size.height < self.tableView.contentSize.height) {
                self.tableView.isScrollEnabled = true
//                UIView.animate(withDuration: 0.32, delay: 0.15, options: UIView.AnimationOptions.curveEaseInOut, animations: {
//                    self.tableView.contentOffset = CGPoint(x: 0, y: self.config.buttonHeight / 0.5)
//                }, completion: { (completion) in
//                    self.tableView.setContentOffset(CGPoint.zero, animated: true)
//                })
            } else {
                self.tableView.isScrollEnabled = false
            }
        })
    }
    
    /// 隐藏ActionSheetView
    public func dismiss(_ needCallback: Bool = true) {
        if needCallback {
            self.clickedHandler?(self, .dismiss)
        }
        hideWithButtonIndex(tag)
    }
    /// 刷新视图
    public func reload() {
        setupSubViews()
    }
}
// MARK: - 全局操作
public extension VHLActionSheetView {
    // MARK: 隐藏所有已弹出的 actionSheet
    static func dismissAll() {
        DispatchQueue.main.async {
            if let keyWindow = UIApplication.shared.windows.filter({ $0.isKeyWindow }).first {
                for view in keyWindow.subviews {
                    if view is VHLActionSheetView {
                        (view as! VHLActionSheetView).dismiss()
                    }
                }
            }
        }
    }
    // MARK: 返回当前所在 window 上的 actionSheet
    class func actionSheet() -> VHLActionSheetView? {
        if let keyWindow = UIApplication.shared.windows.filter({ $0.isKeyWindow }).first {
            for view in keyWindow.subviews {
                if view is VHLActionSheetView {
                    return (view as! VHLActionSheetView)
                }
            }
        }
        return nil
    }
    // MARK: 检查当前 window 是否有弹起的 actionSheet
    class func hasShowed() -> Bool {
        return VHLActionSheetView.actionSheet() != nil
    }
    // MARK: 子视图触发所在 actionSheet 刷新
    class func refreshWithSubView(subView: UIView) {
        var startV: UIView = subView
        while startV.superview != nil {
            if let superV = startV.superview {
                if superV.isKind(of: VHLActionSheetView.self)  {
                    superV.layoutSubviews()
                    break
                } else {
                    startV = superV
                }
            } else {
                break
            }
        }
    }
}

/**

 //    /// 注册通知
 //    func registerNoti() {
 //        // UIApplication.didChangeStatusBarOrientationNotification   状态栏旋转
 //        // UIDevice.orientationDidChangeNotification                 设备选择
 //        // 横竖屏转换通知
 //        NotificationCenter.default.addObserver(self,
 //                                               selector: #selector(handleDeviceOrientationChange(notification:)),
 //                                               name:UIApplication.didChangeStatusBarOrientationNotification,
 //                                               object: nil)
 //    }
 //    @objc private func handleDeviceOrientationChange(notification: Notification) {
 //        guard let superView = self.superview else { return }
 //        self.frame = superView.bounds
 //        setupSubViews()
 //    }
 
 */

/**
   
if let sView = self.superview?.superview {
    sView.layoutIfNeeded()
}
*/
